<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="50%" :title="`坐标位置`">
    <div class="map-dialog-wrapper">
      <div class="map-search-box">
        <el-input
          v-model="mapAddressQuery"
          placeholder="请输入地址查询"
          :prefix-icon="Search"
          @keyup.enter="queryCoord"
          style="flex: 1"
        />
        <el-button @click="queryCoord" type="primary" :icon="Search">查找</el-button>
        <el-button @click="handleMarkJobAddress" type="primary" :icon="Check">记为工作地址</el-button>
      </div>
      <div class="map-box-wrapper">
        <div id="mcontainer" class="map-box"></div>
        <div class="map-query-box"></div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getCoordFromAddress, getAddressFromCoord } from "@/api/modules/common/map";
import { Search, Check } from "@element-plus/icons-vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { ref, shallowRef, watch } from "vue";
import { DialogParam } from "@/biz/interface/DialogType";
import { ElMessage } from "element-plus";

export interface AddressVo {
  provinceName: string;
  cityName: string;
  areaName: string;
  address: string;
  lng: number;
  lat: number;
}

const mapAddressQuery = ref("");
const addressObject = ref({} as any);
const addressLnglat = ref({} as any);

const map = shallowRef(null);
const amap = shallowRef(null);

const mapConfig = {
  key: "ffdc25d48476be43db69ee51b49b80e9",
  version: "2.0",
  plugins: ["AMap.DistrictSearch"]
};

const mapInitInfo = {
  viewMode: "2D",
  zoom: 12,
  center: [105.602725, 37.076636]
};

const initMap = () => {
  AMapLoader.load(mapConfig)
    .then(AMap => {
      map.value = new AMap.Map("mcontainer", mapInitInfo);
      amap.value = AMap;
    })
    .catch(e => console.log(e));
};

let marker = shallowRef(null);
const queryCoord = () => {
  if (mapAddressQuery.value) {
    //先移除点
    if (marker.value) {
      map.value!.remove(marker);
    }

    getCoordFromAddress(mapAddressQuery.value)
      .then(res => res.json())
      .then((res: any) => {
        if (res && res.geocodes) {
          // console.log("查询结果1:", res);

          let coord = res.geocodes[0].location.split(",").map((e: string) => parseFloat(e));
          addressObject.value = { lng: coord[0], lat: coord[1] };

          getAddressFromCoord(res.geocodes[0].location)
            .then(address => address.json())
            .then((ares: any) => {
              // console.log("查询结果2:", ares);
              addressObject.value = ares.regeocode;
              mapAddressQuery.value = ares.regeocode.formatted_address;
            });
          res.geocodes.forEach((geo: any, idx: number) => {
            let coord = geo.location.split(",").map((e: string) => parseFloat(e));
            if (idx == 0) {
              map.value!.setCenter(coord);
              if (coord) {
                addressLnglat.value = { lng: coord[0], lat: coord[1] };
                marker.value = new amap.value!.Marker({
                  position: new amap.value!.LngLat(coord[0], coord[1]),
                  title: geo.formatted_address,
                  draggable: true,
                  cursor: "move"
                });
                marker.value.on("dragend", markerDragEnd);
                map.value!.add(marker.value);
              }
            }
          });
        } else {
          ElMessage.error("未查到,请更精确定位");
        }
      });
  }
};

const markerDragEnd = (e: any) => {
  //根据点的拖动后得到的坐标，重新获取位置信息
  if (e.lnglat) {
    addressLnglat.value = { lng: e.lnglat.lng, lat: e.lnglat.lat };
  }
  if (e.lnglat) {
    getAddressFromCoord(e.lnglat)
      .then(address => address.json())
      .then((ares: any) => {
        addressObject.value = ares.regeocode;
        mapAddressQuery.value = ares.regeocode.formatted_address;
      });
  }
};

const handleMarkJobAddress = () => {
  // console.log("最终返回的坐标位置信息", addressLnglat.value, addressObject.value);
  if (!mapAddressQuery.value) {
    ElMessage.error("请填写详细地址信息");
    return;
  }

  if (Object.keys(addressObject.value).length > 0) {
    // console.log("选定的目标地址", addressObject.value.addressComponent);

    //格式化需要的数据
    if (addressObject.value.addressComponent.district) {
      //这个是格式化后返回的结果
      emits("refresh-data", {
        provinceName: addressObject.value.addressComponent.province,
        cityName: addressObject.value.addressComponent.city,
        areaName: addressObject.value.addressComponent.district,
        address: mapAddressQuery.value,
        ...addressLnglat.value
      });

      dialogVisible.value = false;
    } else {
      ElMessage.error("选择的位置需要精确到区域.");
    }
  } else {
    ElMessage.error("请先进行地址查询！");
  }
};
//弹出框的参数
const dialogVisible = ref(false);

watch(dialogVisible, n => {
  if (n) {
    initMap();
  }
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  console.log("地图组件接收参数", params);
  dialogVisible.value = true;
};

type EmitProps = {
  (e: "refresh-data", val: AddressVo);
};

//页面事件
const emits = defineEmits<EmitProps>();

//页面参数
defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
.map-dialog-wrapper {
  //   border: 1px solid red;
  height: 500px;
  display: flex;
  flex-direction: column;

  .map-search-box {
    z-index: 100;
    width: 90%;
    // height: 60px;
    // border: 1px solid red;
    display: flex;
    // transform: translateY(20px);
    // margin-left: 40px;
  }

  .map-box-wrapper {
    flex: 1;
    margin-top: 10px;
    display: flex;
    // border: 1px solid red;
    .map-box {
      flex: 1;
      // border: 1px solid green;
      height: 100%;
      // transform: translateY(10px);
    }

    .map-query-box {
      // border: 1px solid green;
      // width: 35%;
      width: 1px;
      margin: 0 10px;
    }
  }
}
</style>
